import { EventEmitter } from 'events';
import type { GameObject } from './GameObject';
import type { Engine } from './Engine';

export abstract class Layer extends EventEmitter {
  public ctx: CanvasRenderingContext2D;
  public objects: GameObject[] = [];
  public engine!: Engine;
  
  // 生命周期钩子
  preload?(): Promise<void>;
  abstract create(): void;

  constructor(ctx: CanvasRenderingContext2D) {
    super();
    this.ctx = ctx;
  }

  addObject(obj: GameObject): void {
    this.objects.push(obj);
    obj.layer = this;
    obj.ctx = this.ctx;
  }

  removeObject(obj: GameObject): void {
    const index = this.objects.indexOf(obj);
    if (index > -1) {
      this.objects.splice(index, 1);
      obj.layer = null;
    }
  }

  lookupByType<T extends GameObject>(type: new () => T): T[] {
    return this.objects.filter(
      (obj): obj is T => obj instanceof type
    );
  }
}